<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Set_up;
use App\Models\Filiation;
use App\Models\Wallet;
use Rzy\Smscode\SmsTrait;
use App\Api\Helpers\ApiResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Validator;

class LoginController extends Controller
{
    use SmsTrait;
    use ApiResponse;
    //登录
    public function login()
    { 
        return view('home.login.login');
    }

    public function login_make(Request $request)
    {
        $validate = Validator::make($request->all(),
            [
                'phone' => 'required|exists:users,phone|regex:/^1[34578][0-9]{9}$/',
                'password' => 'required',
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.exists' => '没有该用户',
                'phone.regex' => '手机号格式错误',

                'password.required' => '请输入密码',
            ]
        );
        
        if ($validate->fails()) {
            return $this->ajax_error($validate->errors()->first());
        }

        $user=User::where('phone', $request->phone)->first();
        if (!Hash::check($request->password, $user->password)) {
            return $this->ajax_error('密码错误');
        }
        if($user->status == 1){
            return $this->ajax_error('您的账号未激活');
        }
        if ($user->status==2) {
            return $this->ajax_error('您的账号已被封停');
        }
        $request->session()->put('uid', $user->id);
        //更新用户等级
        $team_num = Filiation::where('top_id', $user->id)->count();
        $s_num = Filiation::where('top_id', $user->id)->where('level', 1)->count();
        if ($team_num >= 50 && $s_num >= 5) {
            $user->level = 2;
        } elseif ($team_num >= 500 && $s_num >= 10) {
            $user->level = 3;
        }
        $user->save();
        session(['user_id'=>$user->id]);
        return $this->ajax_success('登录成功');
    }

    //注册
    public function register(Request $request)
    {
        if (!$request->code) {
            $request->code='';
        }
        return view('home.login.register')->with('code', $request->code);
    }

    public function register_make(Request $request)
    {
        $this->validate(
            $request,
            [
                'phone' => 'required|unique:users|regex:/^1[34578][0-9]{9}$/',
                'password' => 'required',
                'security' => 'required',
                'sms_code' => 'required',
                'code' => 'required'
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.unique' => '该手机号已注册',
                'phone.regex' => '手机号格式错误',

                'password.required' => '请输入密码',

                'security.required' => '请输入安全密码',

                'sms_code.required' => '请输入手机验证码',

                'code.required' => '请输入邀请码'
            ]
        );
        
        $check_sms = $this->checkSmsCode(request('phone'), request('sms_code'), 1);
        if ($check_sms !== true) {
            return redirect("/register/{$request->code}")->with(['code'=>2,'message'=>$check_sms['message']]);
        }

        $user_code = $request->code; //推荐人code
        $recommend_user = User::where('code', $user_code)->first();

        if (!$recommend_user) {
            $pid=0;
        } else {
            $pid=$recommend_user->id;
            $recommend_filiation=Filiation::where('user_id', $recommend_user->id)->orderBy('top_id', 'desc')->get();
        }

        $password = bcrypt($request->password);
        $security = bcrypt($request->security);
        $nickname= $this->get_name();
        $code=$this->get_code();
        
        $data = [
            'phone' => $request->phone,
            'password' => $password,
            'security' => $security,
            'nickname' => $nickname,
            'pid' => $pid,
            'status' => 1,
            'stage' => 1,
            'code' => $code
        ];

        DB::beginTransaction();
        try {
            $user_id = User::insertGetId($data);
            if ($recommend_user) {
                $filiation_data[0]=['user_id'=>$user_id,'top_id'=>$recommend_user->id,'level'=>1];
                $i=0;
                foreach ($recommend_filiation as $k => $v) {
                    $filiation_data[$i+1]=['user_id'=>$user_id,'top_id'=>$v->top_id,'level'=>$k+2];
                    $i++;
                }
                Filiation::insert($filiation_data);
            }
            Wallet::insert(['user_id' => $user_id]);
            DB::commit();
        } catch (QueryException $ex) {
            DB::rollback();
            return redirect("/register/{$request->code}")->with(['code'=>2,'message'=>'注册失败']);
        }
        return redirect('/register')->with(['code'=>1,'message'=>'注册成功']);
    }

    //获取昵称
    public function get_name()
    {
        $nickname='G'.mt_rand(100000, 999999);
        $user=User::where('nickname', $nickname)->first();

        if ($user) {
            return $this->get_name();
        } else {
            return $nickname;
        }
    }

    //获取邀请码
    public function get_code()
    {
        $code=mt_rand(100000, 999999);
        $user=User::where('code', $code)->first();
        if ($user) {
            return $this->get_code();
        } else {
            return $code;
        }
    }

    //发送验证码
    public function send_code(Request $request)
    {
        $this->validate(
            $request,
            [
                'phone' => 'required|regex:/^1[34578][0-9]{9}$/',
                'type' => 'required|max:2|min:1',
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.regex' => '手机号格式错误',

                'type.required' => '验证码类型错误',
                'type.max' => '验证码类型错误',
                'type.min' => '验证码类型错误',
            ]
        );

        $result = $this->sendCodeAndSave($request->phone, $request->type);

        if ($result['success']) {
            return $this->message('发送成功');
        }

        return $this->failed($result['message']);
    }

    //忘记密码
    public function forget()
    {
        return view('home.login.forget');
    }

    public function forget_make(Request $request)
    {
        $this->validate(
            $request,
            [
                'phone' => ['required','exists:users,phone','regex:/^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147)|(145))\\d{8}$/'],
                'password' => 'required|confirmed',
                'sms_code' => 'required',
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.exists' => '没有该用户，请先注册',
                'phone.regex' => '手机号格式错误',

                'password.required' => '请输入密码',
                'password.confirmed' => '密码和确认密码不一致',
                'sms_code' => '请输入手机邀请码',
            ]
        );

        $check_sms = $this->checkSmsCode($request->phone, $request->sms_code, 2);
        if ($check_sms !== true) {
            return redirect('/forget')->with(['code'=>2,'message'=>$check_sms['message']]);
        }
        $password = bcrypt($request->password);
        $data=[
            'password'=>$password,
        ];
        $user=User::where('phone', $request->phone)->update($data);

        if (!$user) {
            return redirect('/forget')->with(['code'=>2,'message'=>'修改失败']);
        }
        return redirect('/login')->with(['code'=>2,'message'=>'修改成功']);
    }
}
